package com.xjscrm.server.biz.mq.producer;

import com.alibaba.fastjson.JSONObject;
import com.uzai.mobile.collect.api.MicaTopics;
import com.uzai.mobile.collect.api.dto.MicaBaseDto;
import com.uzai.mobile.collect.api.dto.MicaTriggerDto;
import com.uzai.mobile.collect.api.enums.MicaMsgType;
import com.uzai.mobile.collect.api.enums.MicaTriggerType;
import com.uzai.trace.TraceGenerate;
import com.xjscrm.common.utils.MqDelayLevel;
import com.xjscrm.common.utils.MqDelayLevelUtil;
import com.xjscrm.common.utils.Tools;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

/**
 * @author lucher
 * @date 2024-03-01 10:41
 */
@Slf4j
@Component
public class SendMsgProducer {
    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    /**
     * 发送瞬时消息
     *
     * @param micaBaseDto
     * @param topic
     * @author lucher
     * @date 2024/3/6 15:31
     */
    @TraceGenerate //注入消息id标签
    public void pushMsg(MicaBaseDto micaBaseDto, String topic) {
        //异步调用MQ发送消息
        String msg = Tools.getStrEmpty(JSONObject.toJSONString(micaBaseDto));
        log.info("--MQ发送消息-topic={}, msg:{}", topic, msg);
        rocketMQTemplate.asyncSend(topic, msg, new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                log.info("--推送消息-成功--topic={}, msg={}", topic, msg);
            }

            @Override
            public void onException(Throwable throwable) {
                log.error("--推送消息-失败--topic={}, msg={}, error:{}", topic, msg, throwable.getMessage());
            }
        }, 3000);
    }

    /**
     * 发送瞬时消息
     *
     * @param micaTriggerDto
     * @param topic
     * @author lucher
     * @date 2024/3/6 15:31
     */
    @TraceGenerate //注入消息id标签
    public void pushMsg(MicaTriggerDto micaTriggerDto, String topic) {
        //异步调用MQ发送消息
        String msg_moblie = Tools.getStrEmpty(JSONObject.toJSONString(micaTriggerDto));
        log.info("--MQ发送手机端消息-topic={}, msg:{}", topic, msg_moblie);
        rocketMQTemplate.asyncSend(topic, msg_moblie, new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                log.info("--推送手机端消息-成功--topic_mobile={}, msg_moblie={}", topic, msg_moblie);
            }

            @Override
            public void onException(Throwable throwable) {
                log.error("--推送手机端消息-失败--topic_mobile={}, msg_moblie={}, error:{}", topic, msg_moblie, throwable.getMessage());
            }
        }, 3000);


        //发送客服聊天系统消息
        if(MicaTriggerType.TRIGGER_CONVERSATION_TALK.getCode().intValue() == micaTriggerDto.getMsgType().intValue()){
            micaTriggerDto.setMsgType(MicaMsgType.SERVER_TALK_MSG.getCode());
            //Data转成JSON字符串发送（悠聊专用这种格式）
            micaTriggerDto.setData(JSONObject.toJSONString(micaTriggerDto.getData()));
            //异步调用MQ发送消息
            String msg_uchant = Tools.getStrEmpty(JSONObject.toJSONString(micaTriggerDto));
            String topic_uchant = MicaTopics.CHAT_TALK_TOPIC;
            //异步调用MQ发送消息
            log.info("--MQ发送客服系统消息-topic_uchant={}, msg_uchant:{}", topic_uchant, msg_uchant);
            rocketMQTemplate.asyncSend(MicaTopics.CHAT_TALK_TOPIC, msg_uchant, new SendCallback() {
                @Override
                public void onSuccess(SendResult sendResult) {
                    log.info("--推送客服系统消息-成功--topic_uchant={}, msg_uchant={}", topic_uchant, msg_uchant);
                }

                @Override
                public void onException(Throwable throwable) {
                    log.error("--推送客服系统消息-失败--topic_uchant={}, msg_uchant={}, error:{}", topic_uchant, msg_uchant, throwable.getMessage());
                }
            }, 3000);
        }
    }

    /**
     * 发送延迟消息
     *
     * @param micaTriggerDto
     * @param delayTopic
     * @author lucher
     * @date 2024/3/6 15:31
     */
    @TraceGenerate //注入消息id标签
    public void pushMsgDelay(MicaTriggerDto micaTriggerDto, String delayTopic) {

        if(!delayTopic.startsWith("delay_")){
            log.info("--延时消息主题出错-delayTopic={}, msg:{}", delayTopic, JSONObject.toJSONString(micaTriggerDto));
        }

        int sumDelay = micaTriggerDto.getDelay();

        //不是延迟队列,调用立即发送队列
        if(sumDelay < 1){
            //去掉延迟topic前缀
            String topic =  delayTopic.replace("delay_","");
            pushMsg(micaTriggerDto, MicaTopics.WW_TRIGGER_TOPIC);
            return;
        }

        MqDelayLevel delayLevel = MqDelayLevelUtil.getLevel(sumDelay);
        int mq_max_delay = delayLevel.getDelay();
        int level = delayLevel.getLevel();
        // 剩余延时
        int leftDelay = sumDelay - mq_max_delay;
        if (leftDelay < 0) {
            leftDelay = 0;
        }
        micaTriggerDto.setDelay(leftDelay);

        String msg = Tools.getStrEmpty(JSONObject.toJSONString(micaTriggerDto));
        log.info("--MQ发送延迟消息-topic={}, msg:{}", delayTopic, msg);

        //封装消息类
        Message<?> message = MessageBuilder.withPayload(msg).build();

        //异步调用MQ发送消息
        rocketMQTemplate.asyncSend(delayTopic, message, new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                log.info("--推送延迟消息-成功--topic={}, msg={}，level={}", delayTopic, msg, mq_max_delay);
            }

            @Override
            public void onException(Throwable throwable) {
                log.error("--MQ推送延迟消息-失败--topic={}, msg={}, error:{}", delayTopic, msg, throwable.getMessage());
            }
        }, 3000, level);
    }

}
